package server.alarmThreads;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;

import server.AlarmServerMain;
import server.container.EinsatzAlarm;

public class FMSSocketConnctor implements Runnable {

	/**
	 * 
	 */
	private static Logger logger = Logger.getLogger(FMSSocketConnctor.class);

	private BlockingQueue<EinsatzAlarm> list;

	public FMSSocketConnctor(BlockingQueue<EinsatzAlarm> list) {

		this.list = list;
	}

	@Override
	public void run() {

		logger.info("Verbinde fms Connector");

		while (true) {

			Scanner sc = null;
			Socket s = null;
			try {

				s = new Socket("alarmapp.chrku.de", 9300);

				PrintWriter writer = new PrintWriter(new BufferedOutputStream(s.getOutputStream()));

				Thread.sleep(4000);

				writer.write("allfms");
				writer.flush();

				writer.write("FMSTlg 16");
				writer.flush();

				sc = new Scanner(new BufferedInputStream(s.getInputStream()));

				while (sc.hasNext()) {

					String in = sc.next();

					if (in.equals("FMSTlg")) {

						logger.info("Neue Nachricht erkannt");
						sc.next();
						sc.next();
						sc.next();
						sc.next();
						String schleife = sc.next();
						String status = sc.next();

						schleife = schleife.substring(0, 2) + "-" + schleife.substring(2);

						logger.info("Schleife " + schleife + " " + status);

						if (schleife.startsWith("0") || schleife.startsWith("95")) {

							String[] einsatz = new String[3];

							einsatz[0] = "fms";
							einsatz[1] = status;
							einsatz[2] = schleife;

							list.put(new EinsatzAlarm(einsatz));
						}

						sc.next();
						sc.next();
						sc.next();
						sc.next();
						sc.next();
						sc.next();
						sc.next();
						sc.next();

					} else {
						logger.info(in);
					}

				}

			} catch (Exception e) {

				e.printStackTrace();
			} finally {

				System.out.println("closed");
				if (sc != null) {
					sc.close();
				}
				if (s != null) {
					try {
						s.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
				}
			}

		}

	}

}
